﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Threading;
using DefaultScope;
using Microsoft.Synchronization.ClientServices.IsolatedStorage;
using System.Collections.ObjectModel;

namespace Klient.Forms
{
    public partial class MySuppliers : PhoneApplicationPage
    {
        #region Dependency Property
        
        public static DependencyProperty AllSuppliersProperty = 
            DependencyProperty.Register(
            "AllSuppliers", 
            typeof(ObservableCollection<Pair<bool, Suppliers>>), 
            typeof(MySuppliers), null);
        
        public ObservableCollection<Pair<bool, Suppliers>> AllSuppliers
        {
            get
            {
                return (ObservableCollection<Pair<bool, Suppliers>>)
                    GetValue(AllSuppliersProperty);
            }
            set
            {
                SetValue(AllSuppliersProperty, value);
            }
        }
        #endregion

        DefaultScopeOfflineContext suppliersContext;
        private string employeeID;
        bool isCacheOpen = false;
        bool isCacheBusy = false;

        public MySuppliers()
        {
            DataContext = this;
            InitializeComponent();
        }

        protected override void OnNavigatedTo(
            System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            suppliersContext = new DefaultScopeOfflineContext("suppliers", 
                new Uri("http://localhost:4000/DefaultScopeSyncService.svc/"));


            if (e.NavigationMode==System.Windows.Navigation.NavigationMode.New 
                && NavigationContext.QueryString.Values.Count > 1)
                {
                    Suppliers supplier = new Suppliers();
                    //wybierz niepowtarzajace sie id
                    supplier.SupplierID = suppliersContext.SuppliersCollection.Max(
                        s => s.SupplierID) + 1;
                    supplier.Region = null;
                    supplier.PostalCode = NavigationContext.QueryString["PostalCode"];
                    supplier.Phone = NavigationContext.QueryString["Phone"];
                    supplier.HomePage = null;
                    supplier.Fax = null;
                    supplier.Country = NavigationContext.QueryString["Country"];
                    supplier.ContactTitle = NavigationContext.QueryString["ContactTitle"];
                    supplier.ContactName = NavigationContext.QueryString["ContactName"];
                    supplier.CompanyName = NavigationContext.QueryString["CompanyName"];
                    supplier.City = NavigationContext.QueryString["City"];
                    supplier.Address = NavigationContext.QueryString["Address"];

                    suppliersContext.AddSuppliers(supplier);
                    suppliersContext.SaveChanges();
            }

            NavigationContext.QueryString.TryGetValue("employeeID", out employeeID);

            suppliersContext.CacheController.ControllerBehavior.SerializationFormat = 
                Microsoft.Synchronization.ClientServices.SerializationFormat.ODataAtom;

            suppliersContext.CacheController.RefreshCompleted += 
                new EventHandler<Microsoft.Synchronization.ClientServices.RefreshCompletedEventArgs>(
                    CacheController_RefreshCompleted);

            suppliersContext.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(
                context_LoadCompleted);

            this.Loaded += new RoutedEventHandler(MySuppliers_Loaded);

            isCacheOpen = true;
        }

        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            if (isCacheBusy)
            {
                e.Cancel = true; //nie wychodź ze strony
                return;
            }
            isCacheOpen = false;
            suppliersContext.Close();
            base.OnNavigatingFrom(e);
        }

        void MySuppliers_Loaded(object sender, RoutedEventArgs e)
        {
            if (isCacheOpen && !isCacheBusy)
            {
                suppliersContext.LoadAsync();
            }
        }

        void context_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            Dispatcher.BeginInvoke(
                delegate
                {
                    progressBar.Visibility = Visibility.Collapsed;
                    if (isCacheOpen)
                    {
                        AllSuppliers = new ObservableCollection<Pair<bool, Suppliers>>(
                            Pair<bool, Suppliers>.createPair(
                                suppliersContext.SuppliersCollection));
                    }
                });
        }

        void CacheController_RefreshCompleted(object sender, 
            Microsoft.Synchronization.ClientServices.RefreshCompletedEventArgs e)
        {
            progressBar.Visibility = Visibility.Collapsed;
            isCacheBusy = false;
            if (isCacheOpen)
            {
                AllSuppliers = new ObservableCollection<Pair<bool, Suppliers>>(
                    Pair<bool, Suppliers>.createPair(suppliersContext.SuppliersCollection));
                if (e.Error != null)
                    Dispatcher.BeginInvoke(delegate { MessageBox.Show(e.Error.ToString()); });
            }
        }

        private void refreshBtn_Click(object sender, RoutedEventArgs e)
        {
            if (isCacheOpen && !isCacheBusy)
            {
                isCacheBusy = true;
                progressBar.Visibility = Visibility.Visible;
                suppliersContext.SaveChanges();
                suppliersContext.CacheController.RefreshAsync();
            }
        }

        private void addBtn_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri(
                "/Forms/NewSupplier.xaml?employeeID=" + employeeID, UriKind.Relative));
        }

        private void deleteBtn_Click(object sender, RoutedEventArgs e)
        {
            if (isCacheOpen & !isCacheBusy)
                isCacheBusy = true;
            {
                progressBar.Visibility = Visibility.Visible;
                foreach (Object o in suppliers.Items)
                {
                    Pair<bool, Suppliers> p = (Pair<bool, Suppliers>)o;
                    if (p.first == true)
                    {
                        suppliersContext.DeleteSuppliers(p.second);
                    }
                }
                suppliersContext.SaveChanges();
                suppliersContext.CacheController.RefreshAsync();
            }
        }
    }
}